import { useRef, useEffect } from 'react';
import type { FC, ReactElement } from 'react';
import Editor from '@/libs/svgEditor';
import type { SvgDrawProps } from '../types';
import { useMemoizedFn, useSafeState } from 'ahooks';
import styles from './styles.module.less';

type WorkspaceProps = SvgDrawProps & {
  children: (editor: Editor) => ReactElement;
}

const SvgEditor: FC<WorkspaceProps> = (props) => {
  const { children, defaultSvg } = props;
  const ref = useRef<HTMLDivElement>(null);
  const [editor, setEditor] = useSafeState<Editor>()

  const initialization = useMemoizedFn(() => {
    const container = ref.current;
    if (!container) return;
    const editor = new Editor(
      container, defaultSvg
    );
    setEditor(editor);
    return () => editor.destroy();
  });

  useEffect(initialization, [initialization]);

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.editor} ref={ref} />
      </div>
      {editor ? children(editor) : null}
    </div>
  );
}

export default SvgEditor;